package com.infore.authorityManagement.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.infore.authorityManagement.dto.Menu;

public class MenuTreeUtil {
	 // list以tree归类
    public static List<Menu> getTree(List<Menu> menus) {
        List<Menu> result = new ArrayList<>();
        List<Menu> list = menus.stream().sorted((obj1, obj2) -> obj1.getSeqNum().compareTo(obj2.getSeqNum())).collect(Collectors.toList());
        List<Menu> treeRoot = getTreeRoot(list);
//        Collections.sort(treeRoot);
        treeRoot.forEach(root -> result.add(getMenu(menus, root,menus)));
        return result;
    }

    /**
    * @Title: getMenu  
    * @Description: 递归过获取无限级子节点
    * @param @param menus
    * @param @param menu
    * @param @return    参数  
    * @return Menu    返回类型  
    * @throws
     */
    private static Menu getMenu(List<Menu> menus, Menu menu, List<Menu> list) {
        List<Menu> childList = getChildList(list, menu);
        if (!CollectionUtils.isEmpty(childList)) {
            childList.forEach(child -> menu.getChildren().add(getMenu(childList, child, list)));
        }
        return menu;
    }

    /**
    * @Title: getTreeRoot  
    * @Description: 获取所有顶级节点 
    * @param @param menus
    * @param @return    参数  
    * @return List<Menu>    返回类型  
    * @throws
     */
    private static List<Menu> getTreeRoot(List<Menu> menus) {
        return menus.stream().filter(menu -> menu.getLevel() == 0).collect(Collectors.toList());
    }

    /**
    * @Title: getChildList  
    * @Description: 得到子节点列表
    * @param @param menus
    * @param @param menu
    * @param @return    参数  
    * @return List<Menu>    返回类型  
    * @throws
     */
    private static List<Menu> getChildList(List<Menu> menus, Menu menu) {
        return menus.stream().filter(menu_ -> StringUtils.isEmpty(menu_.getParentId()) ? false : menu_.getParentId().equals(menu.getId())).collect(Collectors.toList());
    }
}
